<template>
  <div id='stores-container'>
    <stores-header></stores-header>
    <div class="stores-search">
      <el-form :inline="true">
        <el-form-item>
          <el-input placeholder="请输入商品名或店铺名" v-model="keyword" class="stores-search-input">
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button class="stores-search-button" @click="searchShops">搜 索</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div id="map-container"></div>
    <el-dialog v-if="nowSelectedStore !== null" :title="nowSelectedStore.name" :visible.sync="storeDialogVisible" width="30%">
      <span>{{ nowSelectedStore.description }}</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="storeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="gotoStore">前往商店</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'
import { ROUTENAME } from 'services/constConfig.js'
import AMap from 'AMap'
import AMapUI from 'AMapUI'
import StoresHeader from 'components/Header.vue'
import * as notifyUtil from 'utils/notifyUtil.js'
import storesSearch from 'mixins/storesSearch.js'
import userService from 'services/userService.js'
import positionService from 'services/positionService.js'

export default {
  mixins: [storesSearch],
  components: {
    'stores-header': StoresHeader
  },
  data() {
    return {
      storeDialogVisible: false,
      nowSelectedStore: null,
      shops: [],
      keyword: '',
      map: null,
      geocoder: null,
      markers: [],
      addressPredix: '上海市市辖区闵行区',
      lnglat: null
    }
  },
  computed: mapGetters({
    nowStore: 'nowStore',
    nowAddressPredix: 'nowAddressPredix'
  }),
  methods: {
    ...mapActions({
      setNowStore: 'setNowStore',
      setNowAddressPredix: 'setNowAddressPredix'
    }),
    setAddressPredix() {
      // if (this.nowAddressPredix === null) {
      //   if (this.$route.query.addressPredix !== null) {
      //     this.addressPredix = this.$route.query.addressPredix
      //     this.setNowAddressPredix(this.$route.query.addressPredix)
      //   } else {
      //     this.addressPredix = '上海市市辖区闵行区'
      //     this.setNowAddressPredix('上海市市辖区闵行区')
      //   }
      // } else {
      //   this.addressPredix = this.nowAddressPredix
      // }
      if (this.$route.query.addressPredix) {
        this.addressPredix = this.$route.query.addressPredix
      }
    },
    initMap() {
      this.map = new AMap.Map('map-container', {
        resizeEnable: true,
        zoom: 12,
        center: [116.480983, 40.0958]
      })
      AMap.service('AMap.Geocoder', () => {
        this.geocoder = new AMap.Geocoder({})
      })
    },
    setMapCenter() {
      this.geocoder.getLocation(this.addressPredix, (status, result) => {
        if (status === 'complete' && result.info === 'OK') {
          let pos = []
          pos.push(result.geocodes[0].location.lng)
          pos.push(result.geocodes[0].location.lat)
          this.lnglat = new AMap.LngLat(
            result.geocodes[0].location.lng,
            result.geocodes[0].location.lat
          )
          this.map.setCenter(pos)
          this.getLocation()
        } else {
          notifyUtil.showError('定位失败', '请退出后重试')
        }
      })
    },
    getLocation() {
      AMapUI.loadUI(['overlay/AwesomeMarker'], AwesomeMarker => {
        this.chooseUsers(AwesomeMarker)
        for (let i = 0; i < this.shops.length; i++) {
          let shop = this.shops[i]
          this.geocoder.getLocation(shop.address, (status, result) => {
            console.log(result)
            if (status === 'complete' && result.info === 'OK') {
              let position = {
                center:
                  result.geocodes[0].location.lng +
                  ',' +
                  result.geocodes[0].location.lat,
                data: shop
              }
              // this.initMarker(position)
              this.initAwesomeMarker(position, AwesomeMarker)
            } else {
              notifyUtil.showError('商店定位失败', '请退出后重试')
            }
          })
        }
      })
    },
    initAwesomeMarker(position, AwesomeMarker) {
      let awesomeMarker = new AwesomeMarker({
        awesomeIcon: 'shopping-cart',
        iconLabel: {
          style: {
            color: '#ffffff'
          }
        },
        iconStyle: 'darkblue',
        position: position.center.split(','),
        title: position.data.name
      })
      awesomeMarker.setMap(this.map)
      AMap.event.addListener(awesomeMarker, 'click', e => {
        // console.log(position.data)
        this.setNowSelectedStore(position.data)
        this.storeDialogVisible = true
      })
    },
    initUserAwesomeMarker(position, AwesomeMarker) {
      let awesomeMarker = new AwesomeMarker({
        awesomeIcon: 'user',
        iconLabel: {
          style: {
            color: '#ffffff'
          }
        },
        iconStyle: 'red',
        position: position.center.split(',')
      })
      awesomeMarker.setMap(this.map)
      AMap.event.addListener(awesomeMarker, 'click', e => {
        console.log('---------here')
        this.gotoCourier(position.courierId)
      })
    },
    initMarker(position) {
      let marker = new AMap.Marker({
        position: position.center.split(','),
        title: position.data.name
      })
      marker.setMap(this.map)
      AMap.event.addListener(marker, 'click', e => {
        console.log(position.data)
      })
    },
    setShops() {
      if (this.$route.query.shops) {
        this.$set(this, 'shops', JSON.parse(this.$route.query.shops))
      }
    },
    setNowSelectedStore(store) {
      this.$set(this, 'nowSelectedStore', store)
    },
    gotoStore() {
      this.setNowStore(this.nowSelectedStore)
      this.$set(this, 'storeDialogVisible', false)
      this.$router.push({ path: ROUTENAME.STORE })
    },
    gotoCourier(courierId) {
      this.$router.push({
        path: ROUTENAME.COURIER,
        query: {
          courierId: courierId
        }
      })
    },
    chooseUsers(AwesomeMarker) {
      userService.getAllUsers().then(response => {
        if (response.data.User === null || response.data.User === undefined) {
          notifyUtil.showInfo('周围暂无用户', '请稍后再试')
        } else {
          for (let index = 0; index < response.data.User.length; index++) {
            let user = response.data.User[index]
            this.getUserPosition(user.id, AwesomeMarker)
          }
        }
      })
    },
    getUserPosition(userId, AwesomeMarker) {
      positionService.getPosition(userId).then(response => {
        if (
          response.data.Position === null ||
          response.data.Position === undefined
        ) {
          notifyUtil.showInfo('您附近暂无快递员', '请稍后再试')
        } else {
          let userPosition = response.data.Position[0]
          console.log(userPosition)
          let distance = this.lnglat.distance([
            userPosition.lontitude,
            userPosition.latitude
          ])
          // console.log(distance)
          if (distance <= 100000) {
            let position = {
              center: userPosition.lontitude + ',' + userPosition.latitude,
              courierId: userId
            }
            this.initUserAwesomeMarker(position, AwesomeMarker)
          }
        }
      })
    }
  },
  mounted() {
    this.setShops()
    this.setAddressPredix()
    this.initMap()
    if (this.$route.query) {
      this.setMapCenter()
    }
  },
  watch: {
    shops: function() {
      if (this.shops) {
        this.map.clearMap()
        this.setMapCenter()
      }
    }
  }
}
</script>

<style>
.stores-container {
  width: 100%;
  height: 100%;
  bottom: 0;
  background-color: #f7f7f7;
}
.stores-search {
  margin-top: 10px;
  width: 600px;
  height: 30px;
  line-height: 30px;
  font-size: 12px;
  text-align: left;
  margin-left: auto;
  margin-right: auto;
}
.stores-search-input .el-input__inner {
  width: 400px;
  height: 36px;
  color: #606266;
}
.stores-search-button {
  width: 128px;
  height: 36px;
  background-color: #f74342;
  color: #ffffff;
  border: none;
}
#map-container {
  margin-top: 20px;
  width: 1200px;
  height: 800px;
  margin-left: auto;
  margin-right: auto;
  border: 1px solid #e4e7ed;
}
</style>
